// pages/film-SBZP-up/film-SBZP-up.js
const app = getApp();
const db = wx.cloud.database().collection("serve")
const chooseLocation = requirePlugin('chooseLocation');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cname: '',
    business: '',
    contact: '',
    list: '',
    location: '',
    imgUrl:'',
    address: "",
    locationName: "",
    latitude:"",//维度
    longitude:"",//经度
    tempImgUrl: '', // 用于保存暂存图片路径
    tempFiles: [], // 用于暂存图片的数组
    citys: [
      { label: '服化-现代-男', value: '服化-现代-男' },
      { label: '服化-现代-女', value: '服化-现代-女' },
      { label: '服化-古代-男', value: '服化-古代-男' },
      { label: '服化-古代-女', value: '服化-古代-女' },
      { label: '服化-其他', value: '服化-其他' },
      { label: '道具-电器', value: '道具-电器' },
      { label: '道具-家具', value: '道具-家具' },
      { label: '道具-其他', value: '道具-其他' },
    ],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    newModuleIndex: 0, // 新模块的索引，用于唯一标识每个新添加的模块
    cityVisible: false, // 城市选择器是否可见
    cityValue: [], // 城市选择器的值
    filmSBZPList: [], // 租赁设备列表
    ename: '', // 设备名称
  },

  onLoad() {
    // 页面加载时添加一个初始的模块
    this.addFilmSBZP();
  },
  handleDelete(e) {
    const { id } = e.currentTarget.dataset; // 获取当前模块的 moduleId
    const { filmSBZPList } = this.data; // 获取当前设备列表
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 移除对应索引的模块
      filmSBZPList.splice(moduleIndex, 1);
  
      // 更新设备列表数据
      this.setData({
        filmSBZPList
      });
    } else {
      console.error('Module not found');
    }
  },
  // 输入设备名称
  onInputEname(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的 ename
      filmSBZPList[moduleIndex].ename = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  // 输入借用单价
  onInputPrice(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的价格
      filmSBZPList[moduleIndex].price = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  onInputRemark(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的备注
      filmSBZPList[moduleIndex].remark = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  addFilmSBZP() {
    const { newModuleIndex } = this.data;
    const newFilmSBZP = {
      ename: '',
      price: '',
      remark: '',
      originFiles: [],
      cityText: '',
      moduleId: `e${newModuleIndex + 1}`, // 设置模块的 ID
      priceError: false // 添加 priceError 字段用于记录价格输入是否异常
    };
  
    const filmSBZPList = this.data.filmSBZPList || [];
    filmSBZPList.push({ ...newFilmSBZP, index: newModuleIndex });
    const updatedModuleIndex = newModuleIndex + 1;
    this.setData({
      filmSBZPList,
      newModuleIndex: updatedModuleIndex,
    });
  },
  
  
  
  // 在 handleSuccess 方法中获取 moduleId 并设置图片信息
  handleSuccess(e) {
    const moduleId = e.currentTarget.dataset.id; // 获取当前模块的 moduleId
    const { files } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的 originFiles
      filmSBZPList[moduleIndex].originFiles = files;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  handleRemove(e) { 
    console.log('handleRemove called'); 
    const moduleId = e.currentTarget.dataset.id; // 获取当前模块的 moduleId 
    console.log(moduleId)
    const { filmSBZPList } = this.data; 
   
    // 找到对应 moduleId 的模块索引 
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId); 
   
    if (moduleIndex !== -1) { 
      const originFiles = filmSBZPList[moduleIndex].originFiles; 
      const removeIndex = e.detail.index; 
      console.log('removeIndex:', removeIndex); 
   
      if (removeIndex !== undefined) { 
        originFiles.splice(removeIndex, 1); 
      } 
   
      filmSBZPList[moduleIndex].originFiles = originFiles; 
      this.setData({ filmSBZPList }); 
    } else { 
      console.error('Module not found'); 
    } 
  }, 
  handleClick(e) {
    console.log(e.detail.file);
  },

  handleDrop(e) {
    const { files } = e.detail;
    const moduleId = e.currentTarget.dataset.id; // 获取当前模块的 moduleId
    const { filmSBZPList } = this.data;
  
    console.log('Drop event - moduleId:', moduleId);
    console.log('Film SBZP List:', filmSBZPList);
  
    // Find the module by moduleId
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId); 
  
    if (moduleIndex !== -1) { 
      // Update the originFiles of the current module
      const updatedModule = filmSBZPList[moduleIndex];
      updatedModule.originFiles = files;
      filmSBZPList.splice(moduleIndex, 1, updatedModule);
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  
  


    onPickerChange(e) {
    const { value } = e.detail;
    const index = this.data.cityIndex;
    const updatedFilmSBZPList = [...this.data.filmSBZPList];
    updatedFilmSBZPList[index].cityText = value.join(' ');
    this.setData({
      cityVisible: false,
      filmSBZPList: updatedFilmSBZPList,
    });
  },

  onCityPicker(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      cityVisible: true,
      cityIndex: index,
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },
 
  // 数字输入
onPriceInput(e) {
  const { index } = e.currentTarget.dataset; // 获取当前输入框的索引
  const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
  const updatedFilmSBZPList = [...this.data.filmSBZPList];
  updatedFilmSBZPList[index].priceError = !isNumber; // 更新当前输入框的错误状态
  this.setData({
    filmSBZPList: updatedFilmSBZPList,
  });
},



  //地图
  onShow: function () {
    const location = chooseLocation.getLocation();
    if (location) {
      //经纬度，需要存储到数据库中
      console.log(location.latitude)
      console.log(location.longitude)
      this.setData({
        address: location.address ? location.address : "",
        locationName: location.name ? location.name : "",
        location:location.address,
        latitude:location.latitude,
        longitude:location.longitude
        
      });
    }
  },
  showMap() {
    const key = "564BZ-N5WC5-LBFIZ-ISK6L-N3C2O-WJBSQ"; //使用在腾讯位置服务申请的key（必填）
    const referer = "wx6b09b29f03c63446"; //调用插件的app的名称（必填）
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
    });
  },
 

  handleUpload() {
    wx.chooseImage({
      success: chooseResult => {
        const tempImgUrl = chooseResult.tempFilePaths;
        this.setData({
          tempImgUrl: tempImgUrl
        });
      },
    });
  },

    publishRent() {
      const { cname, business, contact, location, address, latitude, longitude, filmSBZPList, tempImgUrl } = this.data;
    
      // 检查是否有未填写的信息
      if (!cname || !business || !contact || !location  || !filmSBZPList.length) {
        wx.showToast({
          title: '请填写完整信息',
          icon: 'error'
        });
        return;
      }
    
      // Check if the price is a valid number
      const isPriceValid = filmSBZPList.every(item => !isNaN(item.price));
    
      if (!isPriceValid) {
        wx.showToast({
          title: '价格必须为数字',
          icon: 'error'
        });
        return;
      }
    
      // 判断是否有需要上传的图片
    const hasTempImages = tempImgUrl && tempImgUrl.length > 0;
    const hasOriginFiles = filmSBZPList.some(item => item.originFiles && item.originFiles.length > 0);
  
    // 如果有需要上传的图片，显示上传提示
    if (hasTempImages || hasOriginFiles) {
      wx.showLoading({
        title: '图片上传中', // Show loading toast for image upload
        mask: true
      });
    }
    
      const picurl = []; // 用于存储上传图片的 URL 的数组
    
      // 遍历 filmSBZPList，逐个处理每个设备条目
      const promises = filmSBZPList.map(item => {
        if (item.originFiles && item.originFiles.length > 0) {
        // 逐个上传图片并将 URL 存储到 picurl 中
        const uploadPromises = item.originFiles.map(file => {
          return new Promise((resolve, reject) => {
            wx.cloud.uploadFile({
              cloudPath: `serve/spicture/${Date.now()}-${Math.floor(Math.random() * 10000000)}.png`, // 设置上传路径
              filePath: file.url, // 获取图片路径
              success: res => {
                console.log('图片上传成功', res);
                const fileID = res.fileID;
                picurl.push({ url: `${fileID}` }); // 将上传成功的图片 URL 存入 picurl 数组
                resolve(fileID); 
              },
              fail: err => {
                console.error('图片上传失败', err);
                reject(err);
              }
            });
          });
        });
    
        return Promise.all(uploadPromises)
          .then(fileIDs => {
            // 图片上传完成后，将设备条目的图片 URL 替换为上传后的 URL
            item.picurl = fileIDs.map(fileID => ({ url: `${fileID}` }));
          })
        }else {
          return Promise.resolve();
        }
      });
    
      // 上传暂存的图片到 equipment/logo/
      const uploadTempImgPromises = hasTempImages ? tempImgUrl.map(url => {
        return new Promise((resolve, reject) => {
          wx.cloud.uploadFile({
            cloudPath: `serve/logo/${Date.now()}-${Math.floor(Math.random() * 10000000)}.png`, // 设置上传路径
            filePath: url, // 获取图片路径
            success: res => {
              console.log('暂存图片上传成功', res);
              resolve(res.fileID); // Resolve with the file ID
              wx.hideLoading();
            },
            fail: err => {
              console.error('暂存图片上传失败', err);
              reject(err);
            }
          });
        });
      }): [];
    
      // 所有设备条目的图片上传完成后，执行数据库提交
      Promise.all([...promises, ...uploadTempImgPromises])
        .then(results => {
          const logoUrl = results.pop(); // Get the last result which is the logo image URL
          // 执行数据库提交
          db.add({
            data: {
              cname,
              business,
              contact,
              location: address,
              location2: [longitude, latitude],
              logo_url: logoUrl, // Update the logo URL with the resolved logo URL
              list: filmSBZPList
            },
          }).then(res => {
            console.log('数据添加成功', res);
            // 清空数据
            this.setData({
              cname: '',
              business: '',
              contact: '',
              location: '',
              address: '',
              latitude: '',
              longitude: '',
              filmSBZPList: [],
              tempImgUrl: [], // 清空暂存图片数组
            });
            wx.showToast({
              title: '发布成功',
              icon: 'success'
            });
          }).catch(err => {
            console.error('数据添加失败', err);
            wx.showToast({
              title: '发布失败，请重试',
              icon: 'none'
            });
          });
        })
        .catch(err => {
          console.error('图片上传失败', err);
          wx.showToast({
            title: '图片上传失败，请重试',
            icon: 'none'
          });
        })
        .finally(() => {
          // 确保在所有图片上传完成后隐藏加载提示
          if (hasTempImages || hasOriginFiles) {
            wx.hideLoading();
          }
        });
    },

    onUnload: function() {
      const pages = getCurrentPages(); 
      if (pages.length >= 2) {
        const prevPage = pages[pages.length - 2]; 
        if (prevPage.getEquipmentData) {
    
          prevPage.getEquipmentData();
        }
      }
      chooseLocation.setLocation(null);
    }
  
})